const Koa = require('koa')
const app = new Koa()

const cors = require('koa2-cors')
const bodyParser = require('koa-bodyparser')
const { connectDb, initSchema } = require('./database/index')

app.use(cors({
  credentials: true, // 传递cookie
  // origin: 'http://localhost:8000'
  origin: 'https://118.25.208.36' // 这里使用ip，不能使用域名

}))
app.use(bodyParser())
connectDb()
initSchema()

app.use(async (ctx, next) => {
  const { url } = ctx.request
  const whiteList = ['/socketIo/user/login', '/socketIo/user/register']
  if (whiteList.includes(url)) {
    await next()
  } else {
    const userId = ctx.cookies.get('userId')
    if (!userId) {
      ctx.body = {
        code: 401, // 未登录或者登录过期
        msg: '您还未登录或者登录期已过，请重新登录',
      }
    } else {
      await next()
    }
  }
})

const Router = require('koa-router')
const router = new Router()
const UserRouter = require('./database/api/user')
const ChatRouter = require('./database/api/chat')
router.use('/socketIo/user', UserRouter.routes())
router.use('/socketIo/chat', ChatRouter.routes())
app.use(router.routes()).use(router.allowedMethods())
const server = require('http').createServer(app.callback())
const io = require('socket.io')(server)
io.on('connection', socket => {
  console.log('server.io成功');
  socket.on('sendChatMsg', data => {
    console.log('server.io接收到消息', data);
    // socket.emit单线通知， io.emit广播通知
    io.emit('receiveChatMsg', data)
  });
  socket.on('disconnect', () => {
    console.log('server.io连接失败')
  });
})

server.listen(3333, () => {
  console.log('server is running %s', 3333)
})